package com.rhino.security.handler;
import com.alibaba.fastjson.JSON;
import com.rhino.security.constants.SecurityConstants;
import com.rhino.security.vo.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录失败操作处理器,登录失败，直接返回错误信息给前端。
 */
@Slf4j
@Component
public class JwtAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        log.info("登录失败：", exception);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(SecurityConstants.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = response.getWriter();

        if (exception instanceof LockedException) {
            //用户被锁定
        } else if (exception instanceof DisabledException) {
            //用户不可用
        }
        //登录失败，统一数据格式，前端根据类型处理。是否重新登录
        RestResult restResult=RestResult.UNAUTH("用户认证失败，请重新登录！");
        writer.write(JSON.toJSONString(restResult));
        writer.close();
    }
}